package com.dingqb.mycs.ui.nativecode;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

import com.base.BaseActivity;
import com.dingqb.mycs.R;
import com.dingqb.mycs.eventbus.UrlEvent;
import com.dingqb.util.InOutStream;

import de.greenrobot.event.EventBus;
/**
 * 原生 网络请求
 * @author DingQingbo
 *
 */
public class UrlConnectionActivity extends BaseActivity {
	private TextView tv_url;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this);
		setContentView(R.layout.activity_native_http);
		tv_url = (TextView) findViewById(R.id.tv_url);
		final String strUrl = "http://api.juheapi.com/japi/toh?key=d9c0b104852bb610edde357b1ece5327&v=1.0&month=12&day=8";
		try {
			urlGet(strUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onEventMainThread(UrlEvent event) {
		String result = event.getResult();
		tv_url.setText(Html.fromHtml(result));

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
/**
 * 原生网络请求
 * @param strUrl
 * @throws Exception
 */
	private void urlGet(final String strUrl) throws Exception {
		new Thread(new Runnable() {
			@Override
			public void run() {
				URL url;
				try {
					url = new URL(strUrl);
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.setDoOutput(true);
					//设置超时时间
					conn.setConnectTimeout(5000);
					// 设置请求方法，默认是GET
					conn.setRequestMethod("GET");
					// 设置字符集
					conn.setRequestProperty("Charset", "UTF-8");
					if (conn.getResponseCode() == 200) {
						InputStream is = conn.getInputStream();
						String result = InOutStream.readInfoStream(is);
						EventBus.getDefault().post(new UrlEvent(result));
					} else {
						EventBus.getDefault().post(new UrlEvent("errorcode=" + conn.getResponseCode()));
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (ProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();

	}

}
